Print a Christmas tree in JavaScript


Posted by Christy on 2023-01-20

Description: Write a function named tree that accepts an number n and print a Christmas tree with the following patterns

tree(1)
*

tree(5)
    *
   ***
  *****
 *******
*********
    *
    *
    *
    *
    *
function tree(n) {
  if (n === 1) return console.log("*");
  // tree
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }

  // trunk
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - 1) + "*");
  }
}

tree(5);









Related Posts

day_03: 我好像有點懂函數式了...

day_03: 我好像有點懂函數式了...

ASP.NET Core Web API 入門教學 - 同時取得父子資料

ASP.NET Core Web API 入門教學 - 同時取得父子資料

自動化測試 x Puppeteer - 玩偶QA參一咖 Day00

自動化測試 x Puppeteer - 玩偶QA參一咖 Day00


Comments